package com.wva.common.utils;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.wva.common.status.Status;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Author: hong
 * @Date: 2025/1/15 12:13:57
 */
@Slf4j
public class WebUtils {
    public static <T> void render(R<T> result, HttpServletResponse response) {
        //将result转为json
        String json = "{\"code\":500999,\"msg\":\"系统异常，请稍后重试\"}";
        try {
            json = new ObjectMapper().writeValueAsString(result);
        } catch (JsonProcessingException e) {
            log.error("exception: JsonProcessingException");
            throw new RuntimeException(e);
        } finally {
            //将json渲染
            render(json, response);
        }
    }

    public static void render(Status status, HttpServletResponse response) {
        R<Object> result = new R<>().code(status.getCode()).message(status.getMessage());
        render(result, response);
    }

    public static void render(String result, HttpServletResponse response) {
        response.setStatus(200);
        try {
            ServletOutputStream outputStream = response.getOutputStream();
            outputStream.write(result.getBytes());
        } catch (IOException e) {
            log.error("IOException: response.getOutputStream()");
        }
    }
}
